package com.hww.v2_mtfsdk;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.hww.common.MyAppThis;
import com.hww.common.util.FileIOUtils;
import com.hww.common.util.ImageUtils;
import com.hww.common.util.LogUtils;
import com.hww.common.util.PermissionUtils;
import com.hww.common.util.SDCardUtils;
import com.hww.common.util.StringUtils;
import com.hww.common.util.ThreadUtils;
import com.hww.common.util.ToastUtils;
import com.hww.v2_mtfsdk.provider.LicenseStatusCallBack;
import com.hww.v2_mtfsdk.provider.SDKV2LicenseManager;
import com.hww.v2_mtfsdk.utils.DialogCustom;

import net.facelib.akcore.AkcoreLog;
import net.facelib.jni.BridgeLog;
import net.facelib.mtfsdk.FaceApiMtfV2Android;
import net.facelib.mtfsdk.FseMtfAndroidBridge;
import net.gdface.sdk.CodeInfo;
import net.gdface.sdk.NotFaceDetectedException;
import net.gdface.sdk.fse.FeatureSe;
import net.gdface.utils.BinaryUtils;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initPermission();
        initView();
        setLogOutput();
    }

    private Button btInit, btRegister, btFace,btSetting;

    private void initView() {
        btInit = findViewById(R.id.bt_init);
        btRegister = findViewById(R.id.bt_register);
        btFace = findViewById(R.id.bt_face);
        btSetting = findViewById(R.id.bt_setting);
        btInit.setOnClickListener(onClickListener);
        btRegister.setOnClickListener(onClickListener);
        btFace.setOnClickListener(onClickListener);
        btSetting.setOnClickListener(onClickListener);
        setBTEnabled(false);
        updateBtInit("init Face SDK (path: /sdcard/license/ )", true);
    }

    /**
     * 设置按钮状态
     *
     * @param enabled true表示授权成功可点击，false表示授权失败不可点击
     */
    private void setBTEnabled(boolean enabled) {
        ThreadUtils.runOnUiThread(() -> {
            if (enabled) {
                btInit.setEnabled(false);
                btRegister.setEnabled(true);
                btFace.setEnabled(true);
            } else {
                btInit.setEnabled(true);
                btRegister.setEnabled(false);
                btFace.setEnabled(false);
            }
        });
    }

    View.OnClickListener onClickListener = v -> {
        switch (v.getId()) {
            case R.id.bt_init:
                updateBtInit("算法初始化中.....", false);
                SDKV2LicenseManager.onlineLicense(new LicenseStatusCallBack() {
                    @Override
                    public void success(String path) {
                        setBTEnabled(true);
                        updateBtInit("授权成功", false);
                        LogUtils.file("SDK_V2LicenseManager", path);
                        mToast(true, "授权成功");
                    }

                    @Override
                    public void failed(String msg) {
                        setBTEnabled(false);
                        updateBtInit("授权失败", true);
                        LogUtils.file("SDK_V2LicenseManager", msg);
                        mToast(false, "授权失败" + msg);
                    }
                }, true);
                break;
            case R.id.bt_register:
                featureGet();
                break;
            case R.id.bt_face:
                Intent intent = new Intent(this, FaceActivity.class);
                startActivity(intent);
                break;
            case R.id.bt_setting:
                DialogCustom.showDialog(MainActivity.this);
                break;

            default:
                break;
        }
    };

    private final int PERMISSIONS_REQUEST_CODE = 0x88;
    private final String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.READ_PHONE_STATE};

    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = PermissionUtils.checkMorePermissions(MainActivity.this, permissions);
            if (permissionList.size() > 0) { // 未授权的权限
                //申请获取权限
                PermissionUtils.requestMorePermissions(MainActivity.this, permissionList, PERMISSIONS_REQUEST_CODE);
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST_CODE:
                PermissionUtils.onRequestMorePermissionsResult(MainActivity.this, permissions, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        showToAppSettingDialog();
                    }
                });
                break;
            default:
                break;
        }
    }

    //显示前往应用设置Dialog
    private void showToAppSettingDialog() {
        new AlertDialog.Builder(this)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PermissionUtils.toAppSetting(MainActivity.this);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void setLogOutput() {
        BridgeLog.BRIDEG_LOGGER.setOutput(message -> {
            String format = String.format("type=%s     msg=%s", "BridgeLog", message);
            LogUtils.file("BRIDEG_LOGGER", format);
        });

        AkcoreLog.AKCORE_LOGGER.setOutput(message -> {
            String format = String.format("type=%s     msg=%s", "AkcoreLog", message);
            LogUtils.file("AKCORE_LOGGER", format);
        });
    }

    private void mToast(boolean status, String msg) {
        runOnUiThread(() -> {
            if (status) {
                ToastUtils.success(MyAppThis.getThis(), msg).show();
            } else {
                ToastUtils.error(MyAppThis.getThis(), msg).show();
            }
        });
    }


    private void featureGet() {
        updateBtAdd("本地照片注册中····", false);
        ThreadUtils.getCpuPool().execute(() -> {
            try {
//                String path = "/mnt/sdcard/face/";
//                String path = SDCardUtils.getExternalFilesDir(null) + "/face/";
                String path = SDCardUtils.getExternalStorageDirectory() + "/face/";
                FileIOUtils.createOrExistsDir(path);
                File pathFile = new File(path);
                File[] sfile = pathFile.listFiles();
                if (null == sfile || sfile.length == 0) {
                    updateBtAdd("文件夹为空: " + path, true);
                    return;
                }

                for (File file : sfile) {
                    registerFeature(file.getAbsolutePath());
                }
            } catch (Exception e) {
                updateBtAdd("exception:" + e.getMessage(), true);
            } finally {
                if (FseMtfAndroidBridge.getFeatureSe().size() > 0) {
                    updateBtAdd(null, false);
                } else {
                    updateBtAdd(null, true);
                }
            }
        });
    }

    private void registerFeature(String path) {
        Bitmap bitmap = ImageUtils.getBitmap(path);
        if (null == bitmap) {
            LogUtils.file(path + "  获取照片失败");
            return;
        }
        try {
            LogUtils.file("faceSDK", "register = " + "本地文件读取成功  " + path);
            CodeInfo[] codeInfos = FaceApiMtfV2Android.getInstance().detectAndGetCodeInfo(bitmap, 0);
            if (null != codeInfos && codeInfos.length > 0) {
                LogUtils.file("照片注册成功  " + path);
                String[] split = path.split("/");
                String s = split[split.length - 1];
                String replace = s.replace(".jpg", "");
                byte[] code = codeInfos[0].getCode();
                addSearchSE(code, Integer.valueOf(replace));
                LogUtils.file("faceSDK", String.format("%s注册成功==len=%s====%s", s, code.length, Thread.currentThread().toString()));
            }
        } catch (NotFaceDetectedException e) {
            mToast(false, "未检测到人脸:" + path);
        } catch (NumberFormatException e) {
            mToast(false, "请使用数字命名照片(例: 1.jpg ):" + path);
        } catch (Exception e) {
            mToast(false, e.getMessage() + "  " + path);
        } finally {
            LogUtils.file("localRegisterFace   finally");
            updateBtAdd("注册成功，成功导入特征码 " + FseMtfAndroidBridge.getFeatureSe().size() + " 个。", false);
        }
    }

    private void addSearchSE(byte[] feature, int name) {
        FeatureSe featureSe = FseMtfAndroidBridge.getFeatureSe();
        if (null != featureSe) {
            try {
                String md5String = BinaryUtils.getMD5String(feature);
                byte[] by = BinaryUtils.hex2Bytes(md5String);
                boolean b = featureSe.addFeature(by, feature, name, 0);
            } catch (Exception e) {
                LogUtils.file(" addFeature " + e.getMessage());
            }
        }
    }

    private void updateBtAdd(String con, boolean enable) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != btRegister) {
                    if (!StringUtils.isEmpty(con)) {
                        btRegister.setText(con);
                    }
                    btRegister.setEnabled(enable);
                }
            }
        });
    }

    private void updateBtInit(String con, boolean enable) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != btInit) {
                    btInit.setText(con);
                    btInit.setEnabled(enable);
                }
            }
        });
    }

}